package com.pp.web.aop;

import com.alibaba.fastjson.JSONObject;
import com.pp.common.bean.ResultBuilder;
import com.pp.common.constant.enums.CoreMsg;
import com.pp.common.exception.BizException;
import com.pp.common.utils.logger.LoggerUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 参数打印、异常处理
 */
@Aspect
@Component
@Slf4j
public class WebAspect implements Ordered{

    public static final String POINTCUT = "execution(public * com.pp.web.controller..*.*(*))";

    @Pointcut(POINTCUT)
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object processor(ProceedingJoinPoint o)  {
        Map reqArgs = (Map)o.getArgs()[0];
        String className = o.getTarget().getClass().getName();
        String method = o.getSignature().getName();
        Throwable ex = null;
        Object result = null;
        try {
            result = o.proceed();
        } catch (Throwable e) {
            //业务异常
            if(e instanceof BizException){
                BizException bizException = (BizException) e;
                result = ResultBuilder.error(bizException.getCode(), bizException.getMsg());
            }else{
                ex = e;
                result = ResultBuilder.error(CoreMsg.UNKNOWN);
            }
        }finally {
            LoggerUtil.printLog(log,className,method, reqArgs,result ,ex);
            return result;
        }
    }


    public int getOrder() {
        return 0;
    }
}

